import { reqCartList, reqDeleteCartById, reqUpdateCheckedByid } from '@/api'
const state = {
  cartList: [],
}
const mutations = {
  GETCARTLIST(state, cartList) {
    state.cartList = cartList
  },
}
const actions = {
  async getCartList({ commit }) {
    let result = await reqCartList()
    if (result.code == 200) {
      commit('GETCARTLIST', result.data)
    }
  },
  async deleteCartListBySkuId({ commit }, skuId) {
    let result = await reqDeleteCartById(skuId)
    if (result.code == 200) {
      // commit('DELETECARTLISTBYSKUID',result.data)
      return 'ok'
    } else {
      return Promise.reject(new Error('faile'))
    }
  },
  // 修改购物车某个产品的选中状态
  async UpdateCheckedById({ commit }, { skuId, isChecked }) {
    let result = await reqUpdateCheckedByid(skuId, isChecked)
    if (result.code == 200) {
      return 'ok'
    } else {
      return Promise.reject(new Error('faile'))
    }
  },
  // 删除全部勾选的产品
  deleteAllCheckedCart({ dispatch, getters, state, commit }) {
    getters.cartList.cartInfoList.forEach((item) => {
      let PromiseAll = []
      let promise =
        item.isChecked == 1 ? dispatch('deleteAllCheckedCart', item.skuId) : ''
      PromiseAll.push(promise)
    })
    return Promise.all(PromiseAll)
  },
  // 修改全部产品的状态
  updateAllCartChecked({ dispatch, state }, isChecked) {
    let promiseAll = []
    state.cartList[0].cartInfoList.forEach((item) => {
      let promise = dispatch('UpdateCheckedById', {
        skuId: item.skuId,
        isChecked,
      })
      promiseAll.push(promise)
    })
    return Promise.all(promiseAll)
  },
}
const getters = {
  cartList(state) {
    return state.cartList[0] || {}
  },
}

export default {
  state,
  mutations,
  actions,
  getters,
}
